import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Tag, Modal, Form, Input, InputNumber, Select, message } from 'antd';
import { PlusOutlined, EditOutlined, SearchOutlined } from '@ant-design/icons';
import axios from 'axios';
import { Product } from '@/types/product';
import { merchantService } from '@/service/merchantService';
import { Pagination } from '@/types/pagination';



const Products: React.FC = () => {
  // 商品列表状态
  const [products, setProducts] = useState<Product[]>([]);

  const [loading, setLoading] = useState<boolean>(false);
  // 分页信息
  const [pagination, setPagination] = useState<Pagination>({
    pageNum: 1,
    pageSize: 10,
    totalSize: 0,
  });
  // 搜索关键词
  const [searchText, setSearchText] = useState<string>('');
  // 模态框可见性
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  // 当前编辑的商品
  const [currentProduct, setCurrentProduct] = useState<Product | null>(null);
  // 表单实例
  const [form] = Form.useForm();

  // 获取商品列表
  const fetchProducts = async (page = pagination.pageNum, pageSize = pagination.pageSize, search = searchText) => {
    setLoading(true);

    const products = await merchantService.getProducts();
    if (!products) {
      message.error('获取商品列表失败');
      setLoading(false);
      return;
    }

    setProducts(products);
    setPagination({
      ...pagination,
      pageNum: page,
      pageSize,
      totalSize: 114514,
    });
    setLoading(false);
  };

  // 首次加载时获取商品列表
  useEffect(() => {
    fetchProducts();
  }, []);

  // 处理表格变化（分页、排序等）
  const handleTableChange = (pagination: any) => {
    fetchProducts(pagination.pageNum, pagination.pageSize);
  };

  // 处理搜索
  const handleSearch = () => {
    fetchProducts(1);
  };

  // 打开新增商品模态框
  const showAddModal = () => {
    setCurrentProduct(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 打开编辑商品模态框
  const showEditModal = (product: Product) => {
    setCurrentProduct(product);
    form.setFieldsValue(product);
    setModalVisible(true);
  };

  // 关闭模态框
  const handleCancel = () => {
    setModalVisible(false);
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();

      if (currentProduct) {
        // 编辑商品
        await axios.put(`/api/merchant/products/${currentProduct.spuId}`, values);
        message.success('商品更新成功');
      } else {
        // 新增商品
        await axios.post('/api/merchant/products', values);
        message.success('商品添加成功');
      }

      setModalVisible(false);
      fetchProducts(); // 重新获取列表
    } catch (error) {
      console.error('提交表单失败:', error);
    }
  };

  // 切换商品状态
  const toggleProductStatus = async (product: Product) => {
    const newStatus = product.isActive ? '在售' : '下架';
    try {
      await axios.put(`/api/merchant/products/${product.spuId}`, {
        ...product,
        status: newStatus,
      });
      message.success(`商品已${newStatus}`);
      fetchProducts(); // 重新获取列表
    } catch (error) {
      message.error('操作失败');
      console.error('切换商品状态失败:', error);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'SKU编号',
      dataIndex: 'skuId',
      key: 'skuId',
    },
    {
      title: '价格(¥)',
      dataIndex: 'price',
      key: 'price',
      render: (price: string) => `¥${price}`,
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === '在售' ? 'green' : 'red'}>
          {status}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Product) => (
        <Space size="middle">
          <Button
            type="primary"
            icon={<EditOutlined />}
            size="small"
            onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          <Button
            type={record.isActive ? 'default' : 'primary'}
            size="small"
            onClick={() => toggleProductStatus(record)}
          >
            {record.isActive ? '下架' : '上架'}
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="p-6">
      <div className="mb-4 flex justify-between items-center">
        <h2 className="text-xl font-bold">商品列表</h2>
        <div className="flex items-center">
          <Input
            placeholder="搜索商品名称或SKU"
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            style={{ width: 250, marginRight: 8 }}
            onPressEnter={handleSearch}
          />
          <Button
            type="primary"
            icon={<SearchOutlined />}
            onClick={handleSearch}
            className="mr-2"
          >
            搜索
          </Button>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={showAddModal}
          >
            添加商品
          </Button>
        </div>
      </div>

      <Table
        dataSource={products}
        columns={columns}
        rowKey="id"
        pagination={{
          current: pagination.pageNum,
          pageSize: pagination.pageSize,
          total: pagination.totalSize,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`,
        }}
        loading={loading}
        onChange={handleTableChange}
      />

      {/* 新增/编辑商品模态框 */}
      <Modal
        title={currentProduct ? '编辑商品' : '新增商品'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={handleCancel}
        width={600}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={currentProduct || {}}
        >
          <Form.Item
            name="name"
            label="商品名称"
            rules={[{ required: true, message: '请输入商品名称' }]}
          >
            <Input placeholder="请输入商品名称" />
          </Form.Item>

          <Form.Item
            name="sku"
            label="SKU编号"
            rules={[{ required: true, message: '请输入SKU编号' }]}
          >
            <Input placeholder="请输入SKU编号" />
          </Form.Item>

          <Form.Item
            name="price"
            label="价格"
            rules={[{ required: true, message: '请输入价格' }]}
          >
            <InputNumber
              min={0}
              precision={2}
              style={{ width: '100%' }}
              placeholder="请输入价格"
              addonBefore="¥"
            />
          </Form.Item>

          <Form.Item
            name="stock"
            label="库存"
            rules={[{ required: true, message: '请输入库存' }]}
          >
            <InputNumber
              min={0}
              style={{ width: '100%' }}
              placeholder="请输入库存"
            />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择商品状态' }]}
          >
            <Select placeholder="请选择商品状态">
              <Select.Option value="在售">在售</Select.Option>
              <Select.Option value="下架">下架</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Products;